<?php
/**
 * Model genrated using LaraAdmin
 * Help: http://laraadmin.com
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Column extends Model
{
    use SoftDeletes;

    protected $table = 'columns';

    protected $hidden = [

    ];

    protected $guarded = [];

    protected $dates = ['deleted_at'];

    protected $appends = ['http_url'];

    protected function _url()
    {
        if (empty($this->url))
            return '#';
        elseif (starts_with($this->url, 'page:'))
            return route('page', [
                $this->getKey(),
                preg_replace('/^page:/', '', $this->url)
            ]);
        elseif (starts_with($this->url, 'goto:')) {
            list(, $id) = preg_split('/:/', $this->url);
            return self::find($id)->http_url;
        } elseif (starts_with($this->url, 'route:')) {
            $params = explode(':', $this->url);
            array_shift($params);
            $route = array_shift($params);
            array_push($params, $this->getKey());
            return route($route, $params);
        } else
            return $this->url;
    }

    public function getHttpUrlAttribute()
    {
        return $this->_url();
    }

    public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function title()
    {
        $title = [];
        $col = $this;
        do {
            $title[] = $col->name;
            $col = $col->parent;
        } while ($col != null);

        return $title;
    }

    public function breadCrumb()
    {
        $breadCrumb = [];
        $col = $this;
        do {
            $breadCrumb[] = ['name' => $col->name, 'url' => $col->http_url];
            $col = $col->parent;
        } while ($col != null);

        return $breadCrumb;
    }

    public function associateColumns()
    {
        return self::where('parent_id', $this->parent_id)->where('parent_id', '>', 0)->orWhere('id', $this->getKey())->get();
    }


}
